import {
  Button,
  Card,
  Col,
  Form,
  message,
  Row,
  Select,
  Space,
  Spin,
  InputNumber,
} from 'antd';
import React, {
  Fragment,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { MyEditor } from '@/components/MyEditor';
import pageStyles from '@/common/pageLayout.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import {
  addVersionService,
  editVersionService,
  getRealTimeVersionDataService,
} from '../services';
import { VersionUpdateContext } from '../common/UpdateContext';
import { getKeyRouter } from '@/utils';
import { VersionManageAPI } from '../common/type';
import { UploadFormCommon } from '@/components/UploadForm';
import { history } from 'umi';
import { IActionEnum } from '../common/UpdateReducer';
import { DirectlyIssueModal } from './DirectlyIssueModal';
import { VersionCheckModal } from './VersionCheckModal';
const UpdateViewLeft: React.FC<VersionManageAPI.IUpdateViewLeft> = ({
  getVersionLoading,
  versionTypeEvent,
}) => {
  const {
    curRes,
    dispatch,
    prefixCls,
    locationProps,
    reloadVersionInfo,
    leftVersionType,
    getVersionDetailData,
  } = useContext(VersionUpdateContext);

  const [updateForm] = Form.useForm();

  /**入口是哪   true为详情 false为新增编辑 */
  const [addOrDetailflag, setAddOrDetailflag] = useState<boolean>(false);

  /**直接签发开关 */
  const [directlyIssue, setDirectlyIssueModal] = useState<boolean>(false);

  /**保留版本号 */
  const [versionFixed, setversionFixed] = useState<number>(0);

  /**
   * 审核modal
   */
  const [checkModal, setCheckModal] = useState<boolean>(false);

  useEffect(() => {
    if (getVersionDetailData && getVersionDetailData?.id) {
      updateForm.setFieldsValue({
        ...getVersionDetailData,
      });
      dispatch({
        type: IActionEnum.LEFT_VERSIONTYPE,
        payload: getVersionDetailData?.versionType,
      });
    } else {
      let params = {
        versionTypeName: 'PC',
      };
      // dispatch({
      //   type: IActionEnum.LEFT_VERSIONTYPE,
      //   payload: '2',
      // });
      getVersionRealDataRun(params);
    }
  }, [getVersionDetailData]);

  /**
   * 获取我的版本回调
   * @param res
   */
  const getRealTimeVersionDataCallBack = (res: any) => {
    if (!(res && res?.msgFlag)) {
      // message.error(res?.msg);
      updateForm?.setFieldsValue({
        publicNum: initPublicNum,
      });
    } else {
      // let version = +(+getVersionRealData?.obj + 0.1).toFixed(1);
      // setversionFixed(version);
      let version = floatObj(0.1, getVersionRealData?.obj, 1);
      setversionFixed(version);
      updateForm?.setFieldsValue({
        publicNum: version,
      });
    }
  };

  /**
   * 获取当前实时的版本信息
   */
  const {
    getVersionRealDataRun,
    getVersionRealDataLoading,
    getVersionRealData,
  } = getRealTimeVersionDataService(getRealTimeVersionDataCallBack);

  const onTypeChange = (value: string) => {
    let params: Record<string, any> = {
      versionTypeName:
        value == '0'
          ? 'Android'
          : value == '1'
          ? 'IOS'
          : value == '2'
          ? 'PC'
          : 'Android',
    };
    getVersionRealDataRun(params);

    dispatch({
      type: IActionEnum.LEFT_VERSIONTYPE,
      payload: value,
    });

    /**左侧选中版本 右侧同步更新 */
    // versionTypeEvent();
  };

  /**
   *
   * @param a 默认加0.1
   * @param b 接口返回的版本值
   * @param digits 保留小数点
   * @returns
   */
  const floatObj = (a: any, b: any, digits: any) => {
    return add(a, b, digits);
  };

  const add = (a: any, b: any, digits: any) => {
    return operation(a, b, digits, 'add');
  };

  /*
   * 核心方法，实现加减乘除运算，确保不丢失精度
   * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
   * @param a {number} 运算数1
   * @param b {number} 运算数2
   * @param digits {number} 精度，保留的小数点数，比如 2, 即保留为两位小数
   * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
   */

  const operation = (a: any, b: any, digits: any, op: any) => {
    let result: number = 0;
    const maxLen = Math.max(getLen(a), getLen(b));
    const base = Math.pow(10, maxLen);
    const bigA = Math.round(base * a);
    const bigB = Math.round(base * b);
    switch (op) {
      case 'add':
        result = bigA + bigB;
        break;
    }
    return result / base;
  };

  /*
   * 将一个浮点数转成整数，返回小数点后面的长度。如 3.14 >> 314，2
   * @param num {number} 小数
   */

  const getLen = (num: any) => {
    let numStr = num.toString();
    return numStr.indexOf('.') === -1 ? 0 : numStr.split('.')[1].length;
  };

  /**
   * 新增编辑回调
   * @param res 接口返回数据
   * @param callType true 为新增回调  || false 为编辑回调
   */
  const updateVersionCallback = (res: any, callType: boolean) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      if (callType) {
        history.push({
          pathname: `/versionController/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            id: res?.obj?.id,
            delRouterName: history.location.pathname, //必传,要删除的路由名称
          },
        });
      } else {
        reloadVersionInfo();
      }
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入新增
   */
  const { addVersionRun, addVersionLoading } = addVersionService(
    updateVersionCallback,
  );
  /**
   * 引入编辑
   */
  const { editVersionRun, editVersionLoading } = editVersionService(
    updateVersionCallback,
  );

  /**添加的时候  点击直接签发/提交审核时  保存一份入参 */
  const [myVersionData, setMyVersionData] = useState<object>({});

  /**
   * 保存版本
   * @param saveType 判断是保存还是直接签发  Save 保存 || Issued 直接签发
   */
  const saveVersion = (saveType: string) => {
    updateForm?.validateFields()?.then((values: any) => {
      if (getVersionDetailData && getVersionDetailData?.id) {
        let updatePayload: any = {
          ...values,
          id: getVersionDetailData?.id,
          versionNum: getVersionDetailData?.versionNum,
          isPublic: 1,
          remark: '',
          versionTypeName:
            values?.versionType == 0
              ? 'Android'
              : values?.versionType == 1
              ? 'IOS'
              : values?.versionType == 2
              ? 'PC'
              : '',
          versionUrl: values?.versionType == 2 ? ' ' : values.versionUrl,
        };
        if (saveType == 'Save') {
          editVersionRun(updatePayload);
        } else if (saveType == 'Issued') {
          setDirectlyIssueModal(true);
        } else if (saveType == 'Apply') {
          setCheckModal(true);
        }
      } else {
        let updatePayload: any = {
          ...values,
          remark: '',
          versionTypeName:
            values?.versionType == 0
              ? 'Android'
              : values?.versionType == 1
              ? 'IOS'
              : values?.versionType == 2
              ? 'PC'
              : '',
          versionUrl: values?.versionType == 2 ? '' : values.versionUrl,
        };
        if (saveType == 'Save') {
          addVersionRun(updatePayload);
        } else if (saveType == 'Issued') {
          setMyVersionData(updatePayload);
          setDirectlyIssueModal(true);
        } else if (saveType == 'Apply') {
          setMyVersionData(updatePayload);
          setCheckModal(true);
        }
      }
    });
  };

  /**
   * 处理是否展示操作按钮框
   */
  const handleOperation = useMemo(() => {
    let isShowBtn: any = {
      allBtnDiv: false, //所有按钮
      issuedBtn: false, //直接签发
      saveBtn: false, //保存
      applyBtn: false, //提交审核
    };

    if (getVersionDetailData?.id) {
      if (
        curRes?.['/versionController/issue'] &&
        (getVersionDetailData?.state == 0 ||
          getVersionDetailData?.state == 1 ||
          getVersionDetailData?.state == 2)
      ) {
        isShowBtn['allBtnDiv'] = true;
        isShowBtn['issuedBtn'] = true;
      }
      if (
        curRes?.['/versionController/apply'] &&
        (getVersionDetailData?.state == 0 || getVersionDetailData?.state == 2)
      ) {
        isShowBtn['allBtnDiv'] = true;
        isShowBtn['applyBtn'] = true;
      }
      if (
        curRes?.['/versionController/edit'] &&
        (getVersionDetailData?.state == 0 || getVersionDetailData?.state == 2)
      ) {
        isShowBtn['allBtnDiv'] = true;
        isShowBtn['saveBtn'] = true;
      }
    } else {
      if (curRes?.['/versionController/issue']) {
        isShowBtn['allBtnDiv'] = true;
        isShowBtn['issuedBtn'] = true;
      }
      if (curRes?.['/versionController/apply']) {
        isShowBtn['allBtnDiv'] = true;
        isShowBtn['applyBtn'] = true;
      }
      if (curRes?.['/versionController/add']) {
        isShowBtn['allBtnDiv'] = true;
        isShowBtn['saveBtn'] = true;
      }
    }

    return isShowBtn;
  }, [curRes, getVersionDetailData]);

  /**版本号禁用 */
  const [publicNumDisable, setPublicNumDisable] = useState<boolean>(false);

  /**没有版本时 默认1.0 */
  const [initPublicNum, setInitPublicNum] = useState<number>(1.0);

  const onStepPublicNum = (value: number) => {
    if (getVersionRealData?.obj && value <= getVersionRealData?.obj) {
      setPublicNumDisable(true);
    }
  };

  return (
    <Fragment>
      <Card
        title={
          getVersionDetailData && getVersionDetailData?.id
            ? '编辑版本'
            : '添加版本'
        }
        className={pageStyles['page-view']}
        bodyStyle={{ height: '90%', padding: '12px 0px 0px' }}
      >
        <Spin
          spinning={
            getVersionLoading || addVersionLoading || editVersionLoading
          }
        >
          <Row className={'cardBodyRow'}>
            <Col span={24} className={'cardBodyCol'}>
              <ScrollBarLayout>
                <div
                  className={pageStyles['fromView-stylesPage']}
                  style={{ padding: '5px 48px 5px 0px' }}
                >
                  <Form
                    form={updateForm}
                    disabled={
                      getVersionDetailData?.id &&
                      (getVersionDetailData.state == '1' ||
                        getVersionDetailData.state == '4')
                        ? true
                        : false
                    }
                  >
                    <Row>
                      <Col span={12}>
                        <Form.Item
                          label={'版本类型'}
                          name="versionType"
                          rules={[
                            {
                              required: true,
                              message: '请选择版本类型',
                            },
                          ]}
                          initialValue={2}
                        >
                          <Select
                            onChange={onTypeChange}
                            placeholder="请选择版本类型"
                            // allowClear
                            disabled={
                              getVersionDetailData && getVersionDetailData?.id
                                ? true
                                : false
                            }
                          >
                            <Select.Option value={0}>安卓端</Select.Option>
                            <Select.Option value={1}>苹果端</Select.Option>
                            <Select.Option value={2}>电脑端</Select.Option>
                          </Select>
                        </Form.Item>
                      </Col>

                      <Col span={12}>
                        <Form.Item
                          label="版本号"
                          name="publicNum"
                          rules={[
                            {
                              required: true,
                              pattern: /\d+(.\d+)*/,
                              message: '请输入正确的版本号',
                            },
                          ]}
                        >
                          <InputNumber
                            placeholder="请输入版本号"
                            defaultValue={
                              getVersionRealData?.obj
                                ? versionFixed
                                : initPublicNum
                            }
                            min={
                              getVersionRealData?.obj
                                ? versionFixed
                                : initPublicNum
                            }
                            step="0.1"
                            stringMode
                            onStep={onStepPublicNum}
                            disabled={
                              /**新增走判断 编辑直接禁用 */
                              getVersionDetailData && getVersionDetailData?.id
                                ? true
                                : publicNumDisable
                            }
                          />
                        </Form.Item>
                      </Col>

                      {/* <Col span={12}>
                        <Form.Item
                          label="版本状态"
                          name="isPublic"
                          rules={[
                            {
                              required: true,
                              message: '请选择版本状态',
                            },
                          ]}
                          initialValue={0}
                        >
                          <Select
                            placeholder="请选择版本状态"
                            allowClear
                            disabled
                          >
                            <Select.Option value={0}>未发布</Select.Option>
                            <Select.Option value={1}>发布上线</Select.Option>
                            <Select.Option value={2}>历史版本</Select.Option>
                          </Select>
                        </Form.Item>
                      </Col>

                      <Col span={12}>
                        <Form.Item
                          label="审批状态"
                          name="checkState"
                          rules={[
                            {
                              required: true,
                              message: '请选择审批状态',
                            },
                          ]}
                          initialValue={4}
                        >
                          <Select
                            placeholder="请选择审批状态"
                            allowClear
                            disabled
                          >
                            <Select.Option value={4}>起草</Select.Option>
                            <Select.Option value={0}>待审核</Select.Option>
                            <Select.Option value={1}>审核通过</Select.Option>
                            <Select.Option value={2}>审核驳回</Select.Option>
                            <Select.Option value={3}>审核作废</Select.Option>
                          </Select>
                        </Form.Item>
                      </Col> */}

                      {leftVersionType != '2' && (
                        <UploadFormCommon
                          form={updateForm}
                          fileFormName={'versionUrl'}
                          spanCol={24}
                          inRowProportion={6}
                          name={'attachFile'}
                          label="应用程序"
                          required={true}
                          accept={'.apk'}
                          url={'/versionController/uploadFile'}
                          downloadUrl={'/versionController/downloadFile'}
                          fileFormDelName={'delFileUrl'}
                          delFunc={() => {}}
                          maxFile={1}
                          defaultFiles={
                            getVersionDetailData && getVersionDetailData?.id
                              ? getVersionDetailData?.versionUrl
                              : null
                          }
                        >
                          上传应用
                        </UploadFormCommon>
                      )}

                      <Col span={24}>
                        <Form.Item
                          label="内容描述"
                          name="upgradeNote"
                          rules={[
                            {
                              required: true,
                              message: '请输入升级内容',
                            },
                          ]}
                        >
                          <MyEditor
                            bodyHeight={300}
                            editorForm={updateForm}
                            formName={'upgradeNote'}
                            editorValue={
                              getVersionDetailData && getVersionDetailData?.id
                                ? getVersionDetailData?.upgradeNote?.contentHtml
                                : ''
                            }
                          />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Form>
                </div>
              </ScrollBarLayout>
              {handleOperation?.allBtnDiv && (
                <div className={'cardBodybtn'}>
                  <Space>
                    {handleOperation?.saveBtn && (
                      <Button
                        type={'primary'}
                        onClick={() => {
                          saveVersion('Save');
                        }}
                      >
                        保存
                      </Button>
                    )}

                    {handleOperation?.issuedBtn && (
                      <Button
                        type={'primary'}
                        onClick={() => {
                          saveVersion('Issued');
                        }}
                      >
                        直接签发
                      </Button>
                    )}

                    {handleOperation?.applyBtn && (
                      <Button
                        type={'primary'}
                        onClick={() => {
                          saveVersion('Apply');
                        }}
                      >
                        提交审核
                      </Button>
                    )}
                  </Space>
                </div>
              )}
            </Col>
          </Row>
        </Spin>
      </Card>
      {/* 发起审核 */}
      {checkModal && (
        <VersionCheckModal
          onClose={() => {
            setCheckModal(false);
          }}
          isShowModal={checkModal}
          checkRows={
            getVersionDetailData?.id ? getVersionDetailData : myVersionData
          }
          reloadVersion={() => {
            reloadVersionInfo();
          }}
          addOrDetailflag={addOrDetailflag}
        />
      )}

      {/* 直接签发 */}
      {directlyIssue && (
        <DirectlyIssueModal
          onClose={() => {
            setDirectlyIssueModal(false);
          }}
          isShowModal={directlyIssue}
          checkRows={
            getVersionDetailData?.id ? getVersionDetailData : myVersionData
          }
          reloadVersion={() => {
            reloadVersionInfo();
          }}
        ></DirectlyIssueModal>
      )}
    </Fragment>
  );
};

export { UpdateViewLeft };
